
package com.bolt.support.dynamic.datasource.tx;

import com.bolt.common.utils.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * 本地事务工具类
 */
public final class LocalTxUtil {


    private static final Logger log = LoggerFactory.getLogger(LocalTxUtil.class);

    /**
     * 手动开启事务
     */
    public static void startTransaction() {
        if (!StrUtil.isEmpty(TransactionContext.getXID())) {
            log.debug("dynamic-datasource exist local tx [{}]", TransactionContext.getXID());
        } else {
            String xid = UUID.randomUUID().toString();
            TransactionContext.bind(xid);
            log.debug("dynamic-datasource start local tx [{}]", xid);
        }
    }

    /**
     * 手动提交事务
     */
    public static void commit() throws Exception {
        try {
            ConnectionFactory.notify(true);
        } finally {
            log.debug("dynamic-datasource commit local tx [{}]", TransactionContext.getXID());
            TransactionContext.remove();
        }
    }

    /**
     * 手动回滚事务
     */
    public static void rollback() throws Exception {
        try {
            ConnectionFactory.notify(false);
        } finally {
            log.debug("dynamic-datasource rollback local tx [{}]", TransactionContext.getXID());
            TransactionContext.remove();
        }
    }
}
